package Client.Dropbox.ServerCommands

import Client.Dropbox.Manager.FileManager
import Client.Dropbox.SystemCommands.SystemListener
import Client.Dropbox.SystemCommands.SumGenerator
import Client.Dropbox.DropboxMain
import java.io.File
import java.io.FileOutputStream
import java.nio.file.Path
import java.nio.file.Files
import objects.File3
import Client.TaggingSystem.TagManager

/**
 * Object that holds the commands that come in from the server
 */
object ServerCommand {
  val root=SystemListener.root.asInstanceOf[Path]
  val user=FileManager.user
  val client=FileManager.client
  
  /**
   * A new file was created on the server
   * @param name the file name
   * @param parent the parent folder
   * @param bytes the bytes that make up the file
   */
  def newFile (name:String, parent:Long, bytes:Array[Byte]){
    val path = root.resolve(FileManager.get(parent)).resolve(name)
    val file=new File(path.toString)
  	val fos=new FileOutputStream(file)
  	fos.write(bytes)
  	fos.flush
  	fos.close
  	TagManager.tag(file)
  }
  
  /**
   * A file was changed on the server
   * @param name the file name
   * @param parent the parent folder
   * @param bytes the bytes that make up the file
   */
  def changedFile (name:String, parent:Long, bytes:Array[Byte]){
    val path = root.resolve(FileManager.get(parent)).resolve(name)
    val file=new File(path.toString)
  	val fos=new FileOutputStream(file)
  	fos.write(bytes)
  	fos.flush
  	fos.close
  }
  
  /**
   * A file was deleted on the server
   * @param name the file name
   * @param parent the parent folder
   */
  def deletedFile (name:String, parent:Long){
    val path = root.resolve(FileManager.get(parent)).resolve(name)
    val file=new File(path.toString)
    file.delete
    TagManager.delete(path.toString)
  }
  
  /**
   * A new folder was created on the server
   * @param name the folder name
   * @param parent the parent folder
   */
  def newFolder (name:String, parent:Long){
    val path = root.resolve(FileManager.get(parent)).resolve(name)
    Files.createDirectory(path)
    SystemListener.register(path)
  }
  
  /**
   * A folder was deleted on the server
   * @param name the folder name
   * @param parent the parent folder
   */
  def deletedFolder (name:String, parent:Long){
    val path = root.resolve(FileManager.get(parent)).resolve(name)
    Files.createDirectory(path)
  }
  
  /**
   * The server is requesting the upload of a new or changed file
   * @param name the file name
   * @param parent the parent folder
   */
  def upload (name:String, parent:Long){
    val par=FileManager.get(parent)
    val p1=root.resolve (par)
    val path=p1.resolve(name)
    val bytes=SumGenerator.toBytes(path)
    val sum=SumGenerator.createCheckSum(path)
    val size=Files.size(path)
    DropboxMain.communicator ! ("upload", new File3 (user, client, name, parent, size, sum, bytes))
  }
}